﻿using General.Core.Data;
using Microsoft.Extensions.Caching.Memory;
using System;
using System.Collections.Generic;
using System.Text;
using System.Linq;
using General.Entities;

namespace General.Services.SysUserRole
{
    public class SysUserRoleService : ISysUserRoleService
    {
        private IMemoryCache _memoryCache;

        private const string MODEL_KEY = "General.services.userRole";
        private GeneralDbContext _generalDbContext;

        public SysUserRoleService(GeneralDbContext generalDbContext,
            IMemoryCache memoryCache)
        {
            this._memoryCache = memoryCache;
            this._generalDbContext = generalDbContext;
        }

        /// <summary>
        /// 获取所有的数据
        /// </summary>
        /// <returns></returns>
        public List<Entities.SysUserRole> GetAll()
        {
            List<Entities.SysUserRole> list = null;
            _memoryCache.TryGetValue<List<Entities.SysUserRole>>(MODEL_KEY, out list);
            if (list != null) return list;
            list = _generalDbContext.SysUserRoles.ToList();
            _memoryCache.Set(MODEL_KEY,list, DateTimeOffset.Now.AddDays(1));
            return list;
        }

        /// <summary>
        /// 移除缓存
        /// </summary>
        public void removeCache()
        {
            _memoryCache.Remove(MODEL_KEY);
        }

        /// <summary>
        /// 保存设置的用户角色数据
        /// </summary>
        /// <param name="userId"></param>
        /// <param name="roleIds"></param>
        public void SaveUserRole(Guid userId, List<Guid> roleIds)
        {
            var list = _generalDbContext.SysUserRoles.Where(o => o.UserId == userId).ToList();
            if (roleIds == null || !roleIds.Any())
                _generalDbContext.SysUserRoles.RemoveRange(list);
            else
            {
                foreach (Guid roleId in roleIds)
                    if (!list.Any(o => o.RoleId == roleId))
                        _generalDbContext.SysUserRoles.Add(new Entities.SysUserRole() { Id = Guid.NewGuid(), RoleId = roleId, UserId = userId });
                foreach (var del in list)
                    if (!roleIds.Any(o => o == del.RoleId))
                        _generalDbContext.SysUserRoles.Remove(del);
            }
            _generalDbContext.SaveChanges();
            removeCache();
        }
    }
}
